import httpx
from app.core.config import settings
from app.core.logger import logger
from typing import Optional, Dict

class WechatService:
    def __init__(self):
        self.app_id = settings.WECHAT_APP_ID
        self.app_secret = settings.WECHAT_APP_SECRET
    
    async def get_openid(self, code: str) -> Optional[str]:
        url = f"https://api.weixin.qq.com/sns/jscode2session"
        params = {
            "appid": self.app_id,
            "secret": self.app_secret,
            "js_code": code,
            "grant_type": "authorization_code"
        }
        
        try:
            async with httpx.AsyncClient() as client:
                response = await client.get(url, params=params)
                data = response.json()
                
                if "openid" in data:
                    logger.info(f"微信登录成功，获取到openid")
                    return data["openid"]
                else:
                    logger.error(f"微信登录失败: {data}")
                    return None
        except Exception as e:
            logger.error(f"微信登录请求失败: {str(e)}")
            return None

wechat_service = WechatService()

